#include <iostream>
#include <string>
#include <mysql/mysql.h>

#define HOST "127.0.0.1"
#define USER "root"
#define PASSWORD "qwertyuiop0723."
#define PORT 3306
#define DBNAME "gobang"

int main()
{
    // 1.初始化mysql句柄
    MYSQL *mysql = mysql_init(nullptr);
    if (mysql == nullptr)
    {
        std::cerr << "mysql init failed" << std::endl;
        return -1;
    }
    // 2.连接服务器
    if (mysql_real_connect(mysql, HOST, USER, PASSWORD, DBNAME, PORT, nullptr, 0) == nullptr)
    {
        std::cerr << "mysql connect failed" << std::endl;
        return -1;
    }
    // 3.设置客户端字符集
    if (mysql_set_character_set(mysql, "utf8") != 0)
    {
        std::cerr << "mysql set character failed" << std::endl;
        return -1;
    }
    // 4.选择要操作的数据库
    if (mysql_select_db(mysql, DBNAME) != 0)
    {
        std::cerr << "mysql select db failed" << std::endl;
        return -1;
    }
    // 5.执行sql语句
    // std::string sql = "insert stu values (1,'小明',18,82.5,98.5,86);";
    // std::string sql = "update stu set name='小红' where id=1;";
    // std::string sql = "delete from stu where id=1;";
    std::string sql = "select * from stu;";
    if (mysql_query(mysql, sql.c_str()) != 0)
    {
        std::cerr << "mysql query failed" << std::endl;
        std::cout << "sql: " << sql << std::endl;
        mysql_close(mysql);
        return -1;
    }
    // 6.如果sql语句是查询语句，则需要保存结果到本地
    MYSQL_RES *res = mysql_store_result(mysql);
    if (res == nullptr)
    {
        mysql_close(mysql);
        return -1;
    }
    // 7.获取结果集中的结果条数
    uint64_t num_row = mysql_num_rows(res);
    int num_col = mysql_num_fields(res);
    // 8.遍历保存到本地的结果集
    for (int i = 0; i < num_row; i++)
    {
        MYSQL_ROW rows = mysql_fetch_row(res);
        for (int j = 0; j < num_col; j++)
        {
            printf("%s\t", rows[j]);
        }
        std::cout << std::endl;
    }
    // 9.释放结果集
    mysql_free_result(res);
    // 10.关闭连接，释放句柄
    mysql_close(mysql);
    return 0;
}